<template>
  <div class="app-container">

    <!-- 角色列表页面--start -->
    <div class="operation">
      <el-button
        type="primary"
        size="small"
        @click="handleForm(null,null)"
      >
        新增角色
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="roleList"
      border
      empty-text="暂无数据"
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        label="角色key"
        align="center"
        width="240"
      >
      </el-table-column>
      <el-table-column
        prop="display_name"
        label="角色名称"
        align="center"
        width="240"
      >
      </el-table-column>
      <el-table-column
        prop="guard_name"
        label="守卫名称"
        align="center"
        width="240"
      >
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间"
        align="center"
        width="240"
      ></el-table-column>
      <el-table-column
        prop="updated_at"
        label="修改时间"
        align="center"
        width="240"
      ></el-table-column>

      <el-table-column
        align="center"
        label="操作"
        prop="id"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="handleForm(scope.$index,scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="handelDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="handlePermission(scope.row)"
          >
            授权
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <paginAtion
      v-on:getNextPageList='getLoading'
      :paginationMeta="pagination"
    ></paginAtion>
    <!-- 角色列表页面--end -->

    <!-- 新增or编辑角色页面---start -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType==='edit'?'编辑角色':'新增角色'"
    >
      <el-form
        v-model="roleObject"
        label-width="80px"
      >

        <el-form-item label="角色KEY">
          <el-input v-model="roleObject.name"></el-input>
        </el-form-item>

        <el-form-item label="角色名称">
          <el-input v-model="roleObject.display_name"></el-input>
        </el-form-item>

      </el-form>
      <div style="text-align:right;">
        <el-button
          type="danger"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          type="primary"
          @click="confirmRole"
        >提交</el-button>
      </div>
    </el-dialog>
    <!-- 新增or编辑角色页面--end -->

    <!--角色授权页面---start -->
    <el-dialog
      :visible.sync='dialogVisiblePermission'
      title="角色授权"
    >
      <el-tree
        empty-text="暂无数据"
        :expand-on-click-node="false"
        :data="menuList"
        :props="defaultProps"
        node-key="id"
        ref="permissionMenuTree"
        default-expand-all
        check-strictly
        show-checkbox
        class="input-tree"
      >

      </el-tree>
      <div class="form-submit operation">
        <el-button
          type="danger"
          @click="dialogVisiblePermission=false"
        >取消</el-button>
        <el-button
          type="primary"
          @click="changeRoleMenu"
        >提交</el-button>
      </div>
    </el-dialog>
    <!-- 角色授权页面--end -->

  </div>
</template>
<script>

import { getRoleList, addRole, deleteRole, getMenusFromRole, changePermissionFromRole } from '@/api/role'
import { getPermissionListFromCurrentUser } from '@/api/permission'
import paginAtion from '@/components/Pagination'

export default {
  components: {
    paginAtion
  },
  data() {
    return {
      roleList: [],
      pagination: {
        current_page: 1,
        from: 1,
        last_page: 1,
        path: '',
        per_page: '5',
        to: 1,
        total: 1
      },
      loading: true,
      dialogVisible: false,
      dialogType: 'new',
      roleObject: {},
      dialogVisiblePermission: false,
      menuList: {},
      defaultProps: {
        id: 'id',
        label: 'display_name',
        children: 'children'
      },
      current_role_id: '',
      permissionList: []
    }
  },
  created() {
    this.init();

  },
  methods: {
    init() {
      const param = { page: this.pagination.current_page, per_page: this.pagination.per_page }
      getRoleList(param)
        .then(
          res => {
            this.loading = false
            if (res.data.length > 0) {
              this.roleList = res.data
              this.pagination = res.meta
            }
          }
        )
        .catch(
          err => {
            this.loading = false
            console.log(err)
          }
        )
      this.getAllPermission()
    },
    /**
     * 翻页
     */
    getLoading(val) {
      this.pagination.current_page = val
      this.loading = true
      this.init()
    },
    /**
     * 新增or编辑角色
     */
    handleForm(index, row) {
      if (row !== null) {
        this.roleObject = row
        this.dialogType = 'edit'
      } else {
        this.roleObject = {}
      }
      this.dialogVisible = true
    },
    /**
     * 删除角色
     */
    handelDelete(row) {
      this.$confirm('此操作将删除该角色及其关联的角色权限，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            deleteRole(row)
              .then(
                res => {
                  this.dialogVisible = false
                  this.$message({ message: '操作成功', type: 'success' })
                  this.init()
                }
              )
              .catch(
                err => {
                  console.log(err)
                }
              )
          }
        )
        .catch(() => {
          console.log('已取消')
        })
    },
    /**
     * 保存角色
     */
    confirmRole() {
      const param = this.roleObject
      addRole(param)
        .then(
          res => {
            this.dialogVisible = false
            this.$message({ message: '操作成功', type: 'success' })
            this.init()
          }
        )
        .catch(
          error => {
            console.log(error)
          }
        )
    },
    /**
     * 角色授权
     */
    handlePermission(row) {
      this.current_role_id = row.id
      const currentCheckNode = []
      this.dialogVisiblePermission = true
      if (row.permissions.length > 0) {
        row.permissions.forEach(item => {
          if (item.pid > 0) {
            currentCheckNode.push(item.id)
          }
        })
      }
      this.$nextTick(() => {
        this.$refs.permissionMenuTree.setCheckedKeys(currentCheckNode);//获取已经设置的资源后渲染
      })
    },
    /**
     * 修改角色权限菜单
     */
    changeRoleMenu() {
      const checkNodes = this.$refs.permissionMenuTree.getCheckedKeys();
      const param = { permission_id: checkNodes }
      var that = this
      //只设置三级
      checkNodes.forEach(item => {
        const currentNodeData = this.$refs.permissionMenuTree.getNode(item)
        if (currentNodeData.level === 2) {
          if (checkNodes.indexOf(currentNodeData.parent.data.id) === -1) {
            checkNodes.push(currentNodeData.parent.data.id)
          }
        }
        if (currentNodeData.level === 3) {
          if (checkNodes.indexOf(currentNodeData.parent.parent.data.id) === -1) {
            checkNodes.push(currentNodeData.parent.parent.data.id)
          }
        }
      })
      changePermissionFromRole(this.current_role_id, param)
        .then(
          res => {
            this.dialogVisiblePermission = false
            this.$message({ message: '操作成功', type: 'success' })
            that.init()
          }
        )
        .catch(
          err => {
            console.log(err)
          }
        )
    },
    cancelSubmit() {
      console.log('取消')
    },
    getAllPermission() {
      getPermissionListFromCurrentUser()
        .then(
          res => {
            this.menuList = res
          }
        )
    }
  }
}
</script>
<style scoped >
.operation {
  padding: 10px 0;
}
.form-submit {
  text-align: right;
}
</style>

